#include "errorui.h"
#include "ui_errorui.h"
#include "constants.h"
#include "controller.h"
#include "log4z.h"
#include <QTimer>
#include <QThread>
#include <QDateTime>

bool bError = true;
extern bool bPowerMonitor;
extern int MAJORVER;
extern int MINORVER;
extern int REVIVER;

void* errBeep(void* ptr)
{
    LOGD("Error beep enter!");
    Controller ettaCtrl;
    unsigned int iPowerShutdown = 0, iPowerSuspend = 0, iPowerLow = 0;
    while (bError)
    {
        system("echo 1 > /sys/class/gpio/gpio111/value");
        system("echo 0 > /sys/class/gpio/gpio112/value");
        system("echo 0 > /sys/class/gpio/gpio60/value");
        if (ettaCtrl.PowerIo() == 0)
        {
            iPowerShutdown++;
            iPowerSuspend = 1;
            iPowerLow = 0;
        }
        else
        {
            iPowerShutdown = 0;
            iPowerLow = 1;
        }
        //Keep for 6s
        if (iPowerShutdown >= 5)
        {
            //reset value
            iPowerShutdown = 0;
            iPowerSuspend = 0;
            iPowerLow == 0;
            LOGFMTD("Func %s: Power key press more t han 6 seconds.", __func__);
            bError = false;
            //shutdown
            system("echo 1 > /sys/class/graphics/fb0/blank");
            system("echo 0 > /sys/class/gpio/gpio113/value");
            LOGD("Power off stop light, rudong, motor, yaodong, door...");
            ettaCtrl.StopLight();
            ettaCtrl.StopRuDong();
            ettaCtrl.StopMotor();
            ettaCtrl.CloseDoor();
            //Default the dianjiguan
            int iSt = ettaCtrl.StartIo();
            int iTot = 0;
            if (iSt == 1)
            {
                //guiwei
                ettaCtrl.SpeedMotor(1);
                ettaCtrl.StartMotor();
                while (iSt == 1 && iTot++ <= 20)
                {
                    QThread::msleep(200);
                    iSt = ettaCtrl.StartIo();
                }
                ettaCtrl.StopMotor();
            }
            ettaCtrl.CloseYao();
            //
            system("echo out > /sys/class/gpio/gpio2/direction");
        }

        system("echo 1 > /sys/class/gpio/gpio113/value");
        QThread::msleep(500);
        system("echo 0 > /sys/class/gpio/gpio113/value");
        QThread::msleep(800);
    }

    system("echo 0 > /sys/class/gpio/gpio113/value");
    return ((void *)0);
}

ErrorUI::ErrorUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ErrorUI)
{
    ui->setupUi(this);
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint );
    //load logo and background
    QPixmap lg(logoStr);
    ui->logo->setPixmap(lg);
    QPixmap bg(backgroundStr);
    QPalette background;
    background.setBrush(QPalette::Background, QBrush(bg));
    setPalette(background);
    ui->errLg->setPixmap(QPixmap(errStr));
    //set font color
    QPalette pe;
    pe.setColor(QPalette::WindowText,Qt::white);
    ui->cTime->setPalette(pe);
    ui->lVer->setPalette(pe);
    ui->title->setPalette(pe);
    ui->subTitle->setPalette(pe);
    ui->info->setPalette(pe);
    ui->info->setText(tr("You could:\n1. Re-start. If fail again, please turn off.\n2. Contact Etta at +86 512 62991988 or service@ettabiotech.com\nSorry for inconvenience it may cause."));
    QString qVer = QString("%1 %2.%3.%4").arg(tr("Version: ")).arg(MAJORVER).arg(MINORVER).arg(REVIVER);
    ui->lVer->setText(qVer);
    //button style
    QPalette btnPe;
    btnPe.setColor(QPalette::ButtonText, Qt::white);
    ui->btnReboot->setPalette(btnPe);
    ui->btnReboot->setStyleSheet(greenBtn);
    QTimer *upTime = new QTimer(this);
    connect(upTime,SIGNAL(timeout()),this,SLOT(updateTime()));
    updateTime();
    upTime->start(1000);
    connect(this, SIGNAL(sendErrCode(QString)), this, SLOT(onError(QString)));
}

ErrorUI::~ErrorUI()
{
    delete ui;
}

void ErrorUI::updateTime()
{
    QDateTime curTime = QDateTime::currentDateTime();
    QString lblTm = curTime.date().toString("yyyy/MM/dd") + "\n " + curTime.time().toString("hh:mm:ss");
    this->ui->cTime->setText(lblTm);
}

void ErrorUI::getShow(QString qErr)
{
    this->show();
    this->activateWindow();
    this->raise();
    //update title
    ui->subTitle->setText(qErr);
    //Let power monitor exit
    bPowerMonitor = false;
    QThread::msleep(800);
    //set error
    Controller ct;
    ct.ErrorIo();
}

void ErrorUI::on_btnReboot_clicked()
{
    bError = false;
    //Let power monitor exit
    bPowerMonitor = false;
    QThread::msleep(800);
    this->close();
    emit sendQuit();
#if defined(__linux__) || defined(__FreeBSD__)
    system("echo 0 > /sys/class/gpio/gpio113/value");
    system("reboot");
#endif
}
